﻿using System;
using System.Collections.ObjectModel;
using System.Xml;

namespace Graphe.Collations
{
    public class LacunateManuscriptCollection : ICollationCollection<Manuscript>, ICollationElement, IComparable<LacunateManuscriptCollection>
    {
        #region ICollationElement Members

        public void Parse(XmlReader reader, CollationDebugMessages debugMessages)
        {
            using (XmlReader subReader = reader.ReadSubtree())
            {
                while (subReader.ReadToFollowing("Manuscript"))
                {
                    Manuscript manuscript = new Manuscript();
                    manuscript.Parse(subReader, debugMessages);
                    Add(manuscript);
                }
            }
        }

        public void Render(XmlTextWriter writer)
        {
            writer.WriteStartElement("Lacuna");
            foreach (Manuscript manuscript in this)
                manuscript.Render(writer);
            writer.WriteEndElement();
        }

        #endregion
        #region IComparable<LacunateManuscriptCollection> Members

        public int CompareTo(LacunateManuscriptCollection other)
        {
            if (Count != other.Count)
                return -1;

            foreach (Manuscript manuscript in this)
            {
                bool foundMatch = false;

                foreach (Manuscript manuscript2 in other)
                {
                    if (manuscript.CompareTo(manuscript2) == 0)
                    {
                        foundMatch = true;
                        break;
                    }
                }

                if (!foundMatch)
                    return -1;
            }

            foreach (Manuscript manuscript in other)
            {
                bool foundMatch = false;

                foreach (Manuscript manuscript2 in this)
                {
                    if (manuscript.CompareTo(manuscript2) == 0)
                    {
                        foundMatch = true;
                        break;
                    }
                }

                if (!foundMatch)
                    return -1;
            }

            return 0;
        }

        #endregion
    }
}
